using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Permissions;
using System.Web.Mvc;
using System.Web.Routing;
using Core.BOL;
using Core.DAL;
using Core.Extentions;
using Core.Utils;

namespace ScoutNET.Controllers
{
    public class CampsController : ApplicationController
    {
        private SectionRepository sr = new SectionRepository();
        private AlbumsRepository ar = new AlbumsRepository();
        private GMapPlaceRepository gr = new GMapPlaceRepository();
        private ImagesRepository ir = new ImagesRepository();

        #region View
        public ActionResult Index(string systemName)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Camps_Index_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Camps_Index_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[2];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = Resources.Camps_Index_Breadcrumb.Replace("[SECTION]", section.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            UserType ut = UsersRepository.GetUserType(systemName);
            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            ViewData["GMapLang"] = ConfigurationManager.AppSettings["Map.Lang"];
            ViewData["DefaultLng"] = ConfigurationManager.AppSettings["Map.Longiture"];
            ViewData["DefaultLat"] = ConfigurationManager.AppSettings["Map.Latitude"];
            ViewData["DefaultZoom"] = ConfigurationManager.AppSettings["Map.Zoom"];
            
            ViewData["ErrorMessage"] = Resources.Camps_Index_ErrorMessage;

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Create(string systemName)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Camps_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Camps_Create_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Camps_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Camps", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Camps_Create_Breadcrumb;
            ViewData["Breadcrumb"] = saBreadcrumb;

            UserType ut = UsersRepository.GetUserType(systemName);
            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            ViewData["GMapLang"] = ConfigurationManager.AppSettings["Map.Lang"];
            ViewData["DefaultLng"] = ConfigurationManager.AppSettings["Map.Longiture"];
            ViewData["DefaultLat"] = ConfigurationManager.AppSettings["Map.Latitude"];
            ViewData["DefaultZoom"] = ConfigurationManager.AppSettings["Map.Zoom"];

            ViewData["SlDateIn"] = new SelectList(GetListYear(true), "Key", "Value");

            List<vw_Site_Photos_Album> lAlbum = ar.GetAlbumBySectionName(systemName);
            ViewData["SlAlbum"] = new SelectList(lAlbum, "ID", "Title");

            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        public ActionResult Create(string systemName, FormCollection fc)
        {
            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Camps_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Camps_Create_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Camps_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Camps", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Camps_Create_Breadcrumb.Replace("[SECTION]", section.ToLower());
            ViewData["Breadcrumb"] = saBreadcrumb;

            UserType ut = UsersRepository.GetUserType(systemName);
            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            if (ValidateNewPlace(fc))
            {
                tSite_Section s = sr.GetSectionsBySystemName(systemName);
                tSite_GMapPlace p = new tSite_GMapPlace();

                ViewData["ValidationMessage"] = Resources.Camps_Create_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());

                p.AID = (!string.IsNullOrEmpty(fc["SlAlbum"])) ? int.Parse(fc["SlAlbum"]) : (int?)null;
                p.City = fc["city"];
                p.Address = fc["address"];
                p.DateCamp = fc["SlDateIn"];
                p.InsertDate = DateTime.Now.GetNowTimeByTimeZone();
                p.SID = s.ID;
                p.Label = fc["city"];
                p.Lat = double.Parse(fc["lat"], System.Globalization.CultureInfo.InvariantCulture);
                p.Lng = double.Parse(fc["lng"], System.Globalization.CultureInfo.InvariantCulture);

                gr.InsertGMapPlaces(p);
                gr.Save();

                List<tSite_GMapPlace> lPlaces = gr.GetMarkersBySectionName(systemName).OrderByDescending(d => d.InsertDate).Take(5).ToList();

                return View("Validation", lPlaces);
            }
            else
            {
                ViewData["GMapLang"] = ConfigurationManager.AppSettings["Map.Lang"];
                ViewData["DefaultLng"] = ConfigurationManager.AppSettings["Map.Longiture"];
                ViewData["DefaultLat"] = ConfigurationManager.AppSettings["Map.Latitude"];
                ViewData["DefaultZoom"] = ConfigurationManager.AppSettings["Map.Zoom"];

                ViewData["lat"] = fc["lat"];
                ViewData["lng"] = fc["lng"];

                ViewData["SlDateIn"] = new SelectList(GetListYear(true), "Key", "Value");

                List<vw_Site_Photos_Album> lAlbum = ar.GetAlbumBySectionName(systemName);
                ViewData["SlAlbum"] = new SelectList(lAlbum, "ID", "Title");
            }
            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Edit(string systemName, int? ID)
        {
            if (ID != null)
            {
                tSite_GMapPlace place = gr.GetPlaceByID((int)ID);

                // Meta Tag
                string section = sr.GetSectionNameBySystemName(systemName).ToLower();
                ViewData["PageTitle"] = Resources.Camps_Create_Title.Replace("[SECTION]", section);
                ViewData["PageDescription"] = Resources.Camps_Create_Description.Replace("[SECTION]", section);

                //Breadcrumb
                string[] saBreadcrumb = new String[3];
                saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
                saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Camps_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Camps", new RouteValueDictionary(new { systemName = systemName }), null);
                saBreadcrumb[2] = Resources.Camps_Edit_Breadcrumb.Replace("[DATE]", place.DateCamp);
                ViewData["Breadcrumb"] = saBreadcrumb;

                UserType ut = UsersRepository.GetUserType(systemName);
                ViewData["UserType"] = ut;
                ViewData["SystemName"] = systemName;

                ViewData["GMapLang"] = ConfigurationManager.AppSettings["Map.Lang"];
                ViewData["DefaultLng"] = ConfigurationManager.AppSettings["Map.Longiture"];
                ViewData["DefaultLat"] = ConfigurationManager.AppSettings["Map.Latitude"];
                ViewData["DefaultZoom"] = ConfigurationManager.AppSettings["Map.Zoom"];


                ViewData["lat"] = place.Lat.ToString(System.Globalization.CultureInfo.InvariantCulture).Replace(',', '.');
                ViewData["lng"] = place.Lng.ToString(System.Globalization.CultureInfo.InvariantCulture).Replace(',', '.');
                ViewData["SlDateIn"] = new SelectList(GetListYear(false), "Key", "Value", place.DateCamp);

                List<vw_Site_Photos_Album> lAlbum = ar.GetAlbumBySectionName(systemName);
                ViewData["SlAlbum"] = new SelectList(lAlbum, "ID", "Title", place.AID);

                return View(place);
            }
            
            return View("Error404");
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        public ActionResult Edit(string systemName, int ID, FormCollection fc)
        {
            tSite_GMapPlace p = gr.GetPlaceByID(ID);

            // Meta Tag
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Camps_Create_Title.Replace("[SECTION]", section);
            ViewData["PageDescription"] = Resources.Camps_Create_Description.Replace("[SECTION]", section);

            //Breadcrumb
            string[] saBreadcrumb = new String[3];
            saBreadcrumb[0] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Master_Breadcrumb_Home, "Default", "Index", "Home", null, null);
            saBreadcrumb[1] = HtmlHelper.GenerateLink(this.ControllerContext.RequestContext, RouteTable.Routes, Resources.Camps_Index_Breadcrumb.Replace("[SECTION]", section), "SectionIndex", "Index", "Camps", new RouteValueDictionary(new { systemName = systemName }), null);
            saBreadcrumb[2] = Resources.Camps_Edit_Breadcrumb.Replace("[DATE]", p.DateCamp);
            ViewData["Breadcrumb"] = saBreadcrumb;

            UserType ut = UsersRepository.GetUserType(systemName);
            ViewData["UserType"] = ut;
            ViewData["SystemName"] = systemName;

            if (ValidateNewPlace(fc))
            {
                ViewData["ValidationMessage"] = Resources.Camps_Edit_Validation.Replace("[USERNAME]", User.Identity.Name.UppercaseFirst());

                p.AID = (!string.IsNullOrEmpty(fc["SlAlbum"])) ? int.Parse(fc["SlAlbum"]) : (int?)null;
                p.City = fc["city"];
                p.Address = fc["address"];
                p.DateCamp = fc["SlDateIn"];
                p.Label = fc["city"];
                p.Lat = double.Parse(fc["lat"], System.Globalization.CultureInfo.InvariantCulture);
                p.Lng = double.Parse(fc["lng"], System.Globalization.CultureInfo.InvariantCulture);
                
                gr.Save();

                List<tSite_GMapPlace> lPlaces = gr.GetMarkersBySectionName(systemName).OrderByDescending(d => d.InsertDate).Take(5).ToList();

                return View("Validation", lPlaces);
            }
            else
            {
                ViewData["GMapLang"] = ConfigurationManager.AppSettings["Map.Lang"];
                ViewData["DefaultLng"] = ConfigurationManager.AppSettings["Map.Longiture"];
                ViewData["DefaultLat"] = ConfigurationManager.AppSettings["Map.Latitude"];
                ViewData["DefaultZoom"] = ConfigurationManager.AppSettings["Map.Zoom"];

                ViewData["lat"] = p.Lat;
                ViewData["lng"] = p.Lng;
                ViewData["SlDateIn"] = new SelectList(GetListYear(false), "Key", "Value", p.DateCamp);

                List<vw_Site_Photos_Album> lAlbum = ar.GetAlbumBySectionName(systemName);
                ViewData["SlAlbum"] = new SelectList(lAlbum, "ID", "Title", p.AID);
            }

            return View(p);            
        }

        [Authorize(Roles = "Animateur,C.U")]
        public ActionResult Delete(string systemName, int ID, int index)
        {
            ViewData["ID"] = ID;
            ViewData["Index"] = index;
            return View();
        }

        [Authorize(Roles = "Animateur,C.U")]
        [HttpPost]
        public JsonResult Delete(string systemName, int ID, FormCollection fc)
        {
            gr.DeletePlace(ID);

            return this.Json(fc["Index"]);
        }
        
        [OutputCache(CacheProfile = "Camp")]
        public JsonResult Markers(string systemName)
        {
            List<tSite_GMapPlace> lGMapPlaces = gr.GetMarkersBySectionName(systemName);
            string mediaDomain = ConfigurationManager.AppSettings["MediaUrl"];

            var query = (from n in lGMapPlaces
                         select new
                         {
                             ID = n.ID,
                             Label = n.Label,
                             City = n.City,
                             Lat = n.Lat,
                             Lng = n.Lng,
                             DateCamp = n.DateCamp,
                             AlbumUrl = (n.tSite_Photos_Album != null) ? Url.Action("Index", new { controller = "Album", SystemName = n.SystemName.UppercaseFirst(), ID = n.tSite_Photos_Album.ID, Title = n.tSite_Photos_Album.Title.ParseUrl() }) : string.Empty,
                             AlbumDefaultImage = (n.tSite_Photos_Album != null && n.tSite_Photos_Album.DefaultImage != null) ? mediaDomain.Substring(0, (mediaDomain.Length - 1)) + Url.RouteUrl("ImageResizer", new { action = "ImageResize", controller = "Camps", Title = n.tSite_Photos_Album.Title.ParseUrl(), ID = n.tSite_Photos_Album.DefaultImage }) : string.Empty,
                             EditURL = Url.Action("Edit", new { ID = n.ID})
                         }).ToList();

            return this.Json(query, JsonRequestBehavior.AllowGet);
        }

        [OutputCache(CacheProfile = "Photo")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public FileResult ImageResize(int ID, string title)
        {
            byte[] baImage = Imaging.GetResizedImage((int)ID, ImageMode.MailThumbnail, true, false);

            return new FileContentResult(baImage, "image/jpeg");
        }

        public ActionResult List(string systemName)
        {
            string section = sr.GetSectionNameBySystemName(systemName).ToLower();
            ViewData["PageTitle"] = Resources.Camps_List_Title.Replace("[SECTION]", section.ToLower());

            List<tSite_GMapPlace> lGMapPlaces = gr.GetMarkersBySectionName(systemName);
            return View(lGMapPlaces);
        }
        #endregion

        #region Methodes
        private Dictionary<string, string> GetListYear(bool blankDate)
        {
            int startYear = DateTime.Now.GetNowTimeByTimeZone().AddYears(-15).Year;
            int endYear = DateTime.Now.GetNowTimeByTimeZone().AddYears(1).Year;
            Dictionary<string, string> lYear = new Dictionary<string, string>();
            if (blankDate)
                lYear.Add("0", string.Empty);

            string years = string.Empty;
            for (int i = startYear; i <= endYear; i++)
            {
                years = i.ToString() + " - " + (i + 1).ToString();
                lYear.Add(years, years);
            }
            return lYear;
        }

        private bool ValidateNewPlace(FormCollection fc)
        {
            ModelState.SetModelValue("address", ValueProvider.GetValue("address"));
            ModelState.SetModelValue("SlDateIn", ValueProvider.GetValue("SlDateIn"));
            ModelState.SetModelValue("lat", ValueProvider.GetValue("lat"));
            ModelState.SetModelValue("lng", ValueProvider.GetValue("lng"));
            ModelState.SetModelValue("city", ValueProvider.GetValue("city"));
            ModelState.SetModelValue("label", ValueProvider.GetValue("label"));

            if (string.IsNullOrEmpty(fc["address"]))
            {
                ModelState.AddModelError("address", Resources.Camps_Create_Error_Address);
            }
            else
            {
                if (string.IsNullOrEmpty(fc["lat"]) || string.IsNullOrEmpty(fc["lng"]) || string.IsNullOrEmpty(fc["city"]))
                {
                    ModelState.AddModelError("address", Resources.Camps_Create_Error_NotLocalized);
                }
            }

            if (fc["SlDateIn"] == "0")
            {
                ModelState.AddModelError("SlDateIn", Resources.Camps_Create_Error_Date);
            }

            return ModelState.IsValid;
        }
        #endregion
    }
}
